package Presenter;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.XML;

import Models.POSGlassWare;

public class POSGlassWarePresenter {
	public ArrayList<POSGlassWare> tryJSONParseArray(String input){
		ArrayList<POSGlassWare> glasswares = new ArrayList<POSGlassWare>();
		try{
			JSONObject jsonObj = null;
			jsonObj = XML.toJSONObject(input);
			JSONObject jsonAllObjects = jsonObj.getJSONObject("pOSGlassWares");
				if(!jsonAllObjects.isNull("posGlassWare")){
					Object item = jsonAllObjects.get("posGlassWare");
					if(item instanceof JSONArray){
						JSONArray jArray = (JSONArray)item;
						for(int i=0; i < jArray.length(); i++){
							JSONObject jObject = jArray.getJSONObject(i);
							glasswares.add(createGlasswareFromJSONObject(jObject));
						}
					} else {
						JSONObject jObject = (JSONObject)item;
						glasswares.add(createGlasswareFromJSONObject(jObject));
					}
				}
			return glasswares;
		} catch(JSONException ex){
			ex.printStackTrace();
		}
		return null;
	}
	
	public POSGlassWare tryJSONParse(String input){
		try{
			JSONObject jsonObj = null;
			jsonObj = XML.toJSONObject(input);
			JSONObject jsonHop = jsonObj.getJSONObject("posGlassWare");
			POSGlassWare glassware = createGlasswareFromJSONObject(jsonHop);
			return glassware;
		} catch(JSONException ex){
			ex.printStackTrace();
		}
		return null;
	}
	
	public POSGlassWare createGlasswareFromJSONObject(JSONObject jsonGlassware){
		POSGlassWare glassware = new POSGlassWare();
		try{
			glassware.setDescription(jsonGlassware.getString("glassWareDescription"));
			glassware.setId(jsonGlassware.getInt("id"));
			glassware.setPackageSize(jsonGlassware.getDouble("size"));
			glassware.setPrePackaged(jsonGlassware.getBoolean("prePackaged"));
			return glassware;
		} catch(JSONException ex){
			ex.printStackTrace();
		} catch(Exception ex){
			ex.printStackTrace();
		}
		return null;
	}
	
	public JSONObject createJSON(POSGlassWare item){
		try{
			JSONObject json = new JSONObject();
			json.put("glassWareDescription", item.getDescription());
			json.put("id", item.getId());
			json.put("size", item.getPackageSize());
			json.put("prePackaged", item.isPrePackaged());
			return json;
		} catch(JSONException ex){
			ex.printStackTrace();
		}
		return null;
	}
}
